package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.dao.AccountDao;
import com.rk.kbk.dao.CashRecordDao;
import com.rk.kbk.dao.PunishLogDao;
import com.rk.kbk.dao.UserDao;
import com.rk.kbk.dto.PageDto;
import com.rk.kbk.model.Account;
import com.rk.kbk.model.CashRecord;
import com.rk.kbk.model.PunishLog;
import com.rk.kbk.model.User;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @PunishLogController
 * @Controller
 * @version : Ver 1.0
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/punishLog")
public class PunishLogController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private PunishLogDao punishLogDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private CashRecordDao cashRecordDao;
    @Autowired
    private AccountDao accountDao;
    @PersistenceContext
    private EntityManager entityManager;

    /**
     * @添加/修改
     * @param punishLog
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdatePunishLog",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdatePunishLog(@RequestBody PunishLog punishLog){
        log.debug("添加/修改");
        punishLogDao.save(punishLog);
        return JsonResp.ok();
    }

    /**
     * @批量添加/修改
     * @param punishLogs
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/addOrUpdateSomePunishLog",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp addOrUpdateSomePunishLog(@RequestBody List<PunishLog> punishLogs){
        log.debug("批量添加/修改");
        punishLogDao.save(punishLogs);
        return JsonResp.ok();
    }

    /**
     * @获取详情-ByPunishLogId
     * @param punishLogId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/punishLogDetails",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPunishLogDetailsByPunishLogId(Long punishLogId) {
        log.debug("获取详情-ByPunishLogId");
        return JsonResp.ok(punishLogDao.findOne(punishLogId));
    }

    /**
     * @分页查询用户处罚记录(jpa方式)
     * @param userId
     * @param pageNum 第几页
     * @param pageSize 每页的条数
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/jpa/page",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findPagePunishLogJpa(Long userId, Integer pageNum, Integer pageSize) {
        log.debug("分页查询用户处罚记录(jpa方式)");
        //多条件排序Sort
        //Sort sort = new Sort(Sort.Direction.DESC, "createdate").and(new Sort(Sort.Direction.AES, "id"));
        //排序Sort
        Sort sort = new Sort(Sort.Direction.DESC, "gmtDatetime");
        Pageable pageable = new PageRequest(pageNum-1, pageSize, sort);
        Page page = null;
        if (null == userId) {
        }else{
            page = punishLogDao.findAll( 		  //条件分页
                    (root, criteriaQuery, cb) -> {
                        Predicate predicate = cb.conjunction();
                        List<Expression<Boolean>> expressions = predicate.getExpressions();
                        User user = userDao.findOne(userId);
                        expressions.add(cb.equal(root.get("us"), user));
                        return predicate;
                    }, pageable);
        }
//        List<PunishLog> content = page.getContent();
//        for (PunishLog punishLog1 : content) {
//        }
        return JsonResp.ok(new PageDto(page));
    }

    /**
     * @删除-one(永久)
     * @param punishLogId
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deletePunishLogOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deletePunishLogOne(Long punishLogId) {
        log.debug("删除-one(永久)");
        punishLogDao.delete(punishLogId);
        return JsonResp.ok();
    }

    /**
     * @批量删除(永久)
     * @param punishLogs
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteSomePunishLog",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteSomePunishLog(@RequestBody List<PunishLog> punishLogs) {
        log.debug("批量删除(永久)");
        punishLogDao.delete(punishLogs);
        return JsonResp.ok();
    }

    /**
     * @处罚用户
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/punishUser",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp punishUser(Long id,Integer punishType,Double punishMoney,Integer punishDays,String punishName) {
        log.debug("处罚用户");
        User user = userDao.findOne(id);
        PunishLog p = new PunishLog();
        //状态处罚
        if(punishType==1){
            user.setServeType(2);
            p.setUs(user);
            p.setStatus(0);
            p.setPunishType(punishType);
            p.setPunishDays(punishDays);
            p.setPunishName(punishName);
            punishLogDao.save(p);
            //判断处罚时间
            Date punishTime=p.getGmtDatetime();
            Date now=new Date();
            int days = (int)((now.getTime() - punishTime.getTime())/86400000);
            if (days-punishDays>0){
                user.setServeType(1);
            }
            userDao.save(user);
        }
        //现金处罚
        if(punishType==2){
            p.setUs(user);
            p.setStatus(0);
            p.setPunishType(punishType);
            p.setPunishMoney(punishMoney);
            p.setPunishName(punishName);
            punishLogDao.save(p);
            //将处罚金额从押金中扣除
            Account account=accountDao.findByUser(user);
            Double money=account.getDepositMoney()-p.getPunishMoney();
            account.setDepositMoney(money);
            accountDao.save(account);
            //在现金记录中存入处罚记录
            CashRecord cashRecord =new CashRecord();
            cashRecord.setMoney(punishMoney);
            cashRecord.setUser(user);
            cashRecord.setOrderType(3);
            cashRecord.setRecoedType(6);
            cashRecord.setMoneyType(2);
            cashRecord.setPayType(4);
            cashRecord.setStatus(1);
            cashRecord.setTitle(punishName);
            if(user.getUserType()==2){
                cashRecord.setGivePerson(2);
            }else if(user.getUserType()==3){
                cashRecord.setGivePerson(1);
            }
            cashRecord.setReceivePerson(0);
            cashRecordDao.save(cashRecord);
            userDao.save(user);
        }
        //系统奖励
        if(punishType==3){
            p.setUs(user);
            p.setStatus(0);
            p.setPunishType(punishType);
            p.setPunishMoney(punishMoney);
            p.setPunishName(punishName);
            punishLogDao.save(p);
            //将处罚金额从押金中扣除
            Account account=accountDao.findByUser(user);
            Double money=account.getDepositMoney()+p.getPunishMoney();
            account.setDepositMoney(money);
            accountDao.save(account);
            //在现金记录中存入处罚记录
            CashRecord cashRecord =new CashRecord();
            cashRecord.setMoney(punishMoney);
            cashRecord.setUser(user);
            cashRecord.setOrderType(3);
            cashRecord.setRecoedType(6);
            cashRecord.setMoneyType(2);
            cashRecord.setPayType(4);
            cashRecord.setStatus(1);
            cashRecord.setTitle(punishName);
            if(user.getUserType()==2){
                cashRecord.setGivePerson(2);
            }else if(user.getUserType()==3){
                cashRecord.setGivePerson(1);
            }
            cashRecord.setReceivePerson(0);
            cashRecordDao.save(cashRecord);
            userDao.save(user);
        }

        return JsonResp.ok();
    }




}
